package com.ruizhong.centercontroll.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Hash {
    /**
     * 模拟Shiro的Md5Hash实现
     * @param password 原始密码
     * @param salt 盐值（如用户名）
     * @param iterations 迭代次数
     * @return 加密后的十六进制字符串
     */
    public static String md5Hash(String password, String salt, int iterations) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 合并密码和盐值
            byte[] combined = (password + salt).getBytes();
            
            // 多次迭代哈希
            byte[] hash = combined;
            for (int i = 0; i < iterations; i++) {
                hash = md.digest(hash);
                md.reset(); // 重置以进行下一次迭代
            }
            
            // 转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = String.format("%02x", b);
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }
}